package com.sso.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sso.utils.CookieUtils;

@Controller
public class LoginController extends BaseController {

	@RequestMapping("/login")
	public String login(Model model) {

		String returnUrl = request.getParameter("ReturnURL");
		String token = (String) request.getAttribute("SSOToken");
		if (StringUtils.isBlank(token)) {
			String name = request.getParameter("name");
			if (name != null && !"".equals(name)) {
				/*
				 * 设置登录 Cookie
				 * 最后一个参数 true 时添加 cookie 同时销毁当前 JSESSIONID 创建信任的 JSESSIONID
				 */
				CookieUtils.authJSESSIONID(request, "SSO");
				CookieUtils.setCookie(request, response, "SSO-TOKEN", name);
				// 重定向到指定地址 returnUrl
				if (StringUtils.isEmpty(returnUrl)) {
					returnUrl = "/index.html";
				}
				return redirectTo(returnUrl);
			} else {
				if (StringUtils.isNotEmpty(returnUrl)) {
					model.addAttribute("ReturnURL", returnUrl);
				}
				return "login";
			}
		} else {
			if (StringUtils.isEmpty(returnUrl)) {
				returnUrl = "/index.html";
			}
			return redirectTo(returnUrl);
		}
	}

	@RequestMapping("/index")
	public String index(Model model) {
		String token="";
		try {
			token = CookieUtils.getCookieValue(request, "SSO-TOKEN");
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.err.println(token);
		if(StringUtils.isBlank(token)) {
			return "redirect:/login";
		}
		
		model.addAttribute("token", token);
		return "index";
	}


	/**
	 * 统一退出，调用对外提供退出的所有接口
	 */
	@RequestMapping("/logout")
	public String logout() {
	//	SSOHelper.clearLogin(request, response);
		CookieUtils.deleteCookie(request, response, "SSO-TOKEN");
		return "logout";
	}

	/**
	 * 退出 SSO 登录
	 */
	@RequestMapping("/logsso")
	public String logsso() {
		/*
		 * <p>
		 * SSO 退出，清空退出状态即可
		 * </p>
		 * 
		 * <p>
		 * 子系统退出 SSOHelper.logout(request, response); 注意 sso.properties 包含 退出到
		 * SSO 的地址 ， 属性 sso.logout.url 的配置
		 * </p>
		 */
	//	SSOHelper.clearLogin(request, response);
		CookieUtils.deleteCookie(request, response, "SSO-TOKEN");
		return redirectTo("/login.html");
	}
	
	
	
}
